package com.cloud.nacosConfigLoad;

import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.DefaultSingletonBeanRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

/**
 * Bean 管理类，负责销毁和重新注入 Bean
 */
@Component
public class BeanManager {

    private final ConfigurableListableBeanFactory beanFactory;

    // 构造方法，获取 Spring 的 Bean 工厂
    public BeanManager(ApplicationContext applicationContext) {
        this.beanFactory = (ConfigurableListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
    }

    /**
     * 重新加载 Bean，如果 Bean 已经存在，则销毁原来的实例并注册新的实例
     *
     * @param beanName        Bean 名字
     * @param newBeanInstance 新的 Bean 实例
     */
    public void reloadBean(String beanName, Object newBeanInstance) {
        if (beanFactory.containsBean(beanName)) {
            // 获取 DefaultSingletonBeanRegistry 并销毁原单例 Bean
            if (beanFactory instanceof DefaultSingletonBeanRegistry) {
                ((DefaultSingletonBeanRegistry) beanFactory).destroySingleton(beanName); // 销毁原来的 Bean 实例
            }
        }
        beanFactory.registerSingleton(beanName, newBeanInstance); // 注册新的 Bean 实例
        System.out.println("Bean reloaded: " + beanName);
    }
}
